//
//  RNIOSExportJsToReact.m
//  xmgjAppFront
//
//  Created by 汪滔 on 2020/7/1.
//

#import <Foundation/Foundation.h>
#import "BridgeManager.h"
#import <React/RCTLog.h>
#import "GJMapViewController.h"
#import "GJAddressSearchViewController.h"
#import "GJRouter.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "GJIPUtil.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "AppDelegate.h"
@implementation BridgeManager

RCT_EXPORT_MODULE();


RCT_EXPORT_METHOD(initlizationBaseUrlString:(NSString *) baseUrlString){
  dispatch_async(dispatch_get_main_queue(), ^{
    [GJNetworkPrefix sharedInstance].networkPrefix = baseUrlString;
    [GJUtil checkVersion:^(BOOL showToast) {
      
    }];
  });
}


RCT_EXPORT_METHOD(getAppVersion:(RCTResponseSenderBlock) callback){
  NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
  callback(@[version]);
}
//跳转地图页面
RCT_EXPORT_METHOD(startActivity:(NSString *)appVersion businessNo:(NSString *) businessNo){
  dispatch_async(dispatch_get_main_queue(), ^{
    
    if (![GJUtil hasLocationAuthorization]) {
      [UIAlertController showAlertInViewController:[UIApplication sharedApplication].keyWindow.rootViewController withTitle:@"请允许访问位置信息" message:@"我们将获取您的位置信息，用于展示你的当前地址" cancelButtonTitle:@"取消" destructiveButtonTitle:@"同意" otherButtonTitles:nil tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
              [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
      }];
      return;
    }
    
    NSDictionary *jsonDic = [businessNo jsonValueDecoded];
    GJMapViewController *vc = [GJMapViewController new];
    vc.businessNo = [jsonDic objectForKey:@"businessNo"];
    vc.modalPresentationStyle =  UIModalPresentationFullScreen;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:vc animated:YES completion:nil];
  });
}
//点击导航
RCT_EXPORT_METHOD(mapNavigation:(double)startLat startLon:(double)startLon endLat:(double)endLat endLon:(double)endLon endName:(NSString *)endName ){
  dispatch_async(dispatch_get_main_queue(), ^{
    CLLocationCoordinate2D endCoordinate = CLLocationCoordinate2DMake(endLat, endLon);
    //将GPS转成高德坐标
    CLLocationCoordinate2D amapcoord = AMapCoordinateConvert(endCoordinate, AMapCoordinateTypeBaidu);
    [GJUtil openURLMapNavgationLocation:amapcoord];
  });
}

//获取设备信息
RCT_EXPORT_METHOD(getSystemInfo:(RCTResponseSenderBlock) callback){
  callback(@[@{
               @"model":[GJUtil currentModel],
               @"appVersion":[UIApplication sharedApplication].appVersion,
               @"os":@"ios",
               @"ip":[GJUtil GJ_getGateWay],
               @"imei":[GJUtil GJ_getUUID],
               @"brand":@"apple",
               @"deviceId":[GJUtil GJ_getUUID],
               @"deviceBankId":[GJUtil GJ_getUUID],
               @"simCardNumber":@"",
               @"simCardNum":@([GJUtil SimCardNumInPhone]),
               @"deviceName": [GJUtil currentModel],
               @"deviceType":@"01",
               @"appType":@"ios",
               @"Mac":@"",
               @"ipAddress":@"",
               @"ipVersion":[GJIPUtil isIpv6] ? @"ipv6" : @"ipv4",
               @"sysVersionNum":[UIDevice currentDevice].systemVersion
               
  }]);
}
///路由跳转
RCT_EXPORT_METHOD(startRouteActivity:(NSString *)urlStirng){
  if ([urlStirng gj_hasValue]) {
    dispatch_async(dispatch_get_main_queue(), ^{
      //地图选点
      UIViewController *vc = [GJRouter openURL:urlStirng];
      if (vc) {
        vc.modalPresentationStyle =  UIModalPresentationFullScreen;
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:vc animated:YES completion:nil];
      }
    });
  }
}

///路由跳转
RCT_EXPORT_METHOD(iosLockToPortrait){
    dispatch_async(dispatch_get_main_queue(), ^{
      [[NSNotificationCenter defaultCenter] postNotificationName:GJKGJChangeRNOrientationNotification object:nil userInfo:@{@"action":@"1"}];
    });
  
}
///路由跳转
RCT_EXPORT_METHOD(iosLockToLandscape){
    dispatch_async(dispatch_get_main_queue(), ^{
      [[NSNotificationCenter defaultCenter] postNotificationName:GJKGJChangeRNOrientationNotification object:nil userInfo:@{@"action":@"2"}];
    });
  
}


RCT_EXPORT_METHOD(openSettings:(RCTPromiseResolveBlock)resolve
                  reject:(__unused RCTPromiseRejectBlock)reject)
{
  dispatch_async(dispatch_get_main_queue(), ^{
     NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
      if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
          if (success) {
            resolve(nil);
          } else {
            reject(RCTErrorUnspecified, @"Unable to open app settings", nil);
          }
        }];
      } else {
    #if !TARGET_OS_UIKITFORMAC
       // Note: This branch will never be taken on UIKitForMac
       BOOL opened = [RCTSharedApplication() openURL:url];
       if (opened) {
         resolve(nil);
       } else {
         reject(RCTErrorUnspecified, @"Unable to open app settings", nil);
       }
    #endif
      }
  });
}


///路由跳转
RCT_EXPORT_METHOD(iOSIQKeyaboard:(BOOL)isOpen){
    dispatch_async(dispatch_get_main_queue(), ^{
      [IQKeyboardManager sharedManager].enable = isOpen; // 控制整个功能是否启用
    });
}
///横屏
RCT_EXPORT_METHOD(iosLockToLandscape:(BOOL) isAllow){
  dispatch_async(dispatch_get_main_queue(), ^{
//
//    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    // 打开横屏开关
//    appDelegate.allowRotation = isAllow;
    [self changeOrientation:isAllow];
  });
}

- (void)changeOrientation:(BOOL)isAllow{
  
  UIInterfaceOrientation orientation = UIInterfaceOrientationLandscapeLeft;
  if (isAllow) {
    orientation = UIInterfaceOrientationLandscapeLeft;
    //设置statusBar
    [UIApplication sharedApplication].statusBarHidden = YES;
  }else{
    //设置statusBar
    [UIApplication sharedApplication].statusBarHidden = NO;
    orientation = UIInterfaceOrientationPortrait;
  }
    
  
  
  //计算旋转角度
  float arch;
  if (orientation == UIInterfaceOrientationLandscapeLeft)
      arch = -M_PI_2;
  else if (orientation == UIInterfaceOrientationLandscapeRight)
      arch = M_PI_2;
  else
      arch = 0;
  
 
  [UIView animateWithDuration:0.3 animations:^{
    [UIApplication sharedApplication].keyWindow.rootViewController.view.transform = CGAffineTransformMakeRotation(arch);
    //对view 进行强制旋转
    [UIApplication sharedApplication].keyWindow.rootViewController.view.bounds = UIInterfaceOrientationIsLandscape(orientation) ? CGRectMake(0, 0, kScreenHeight, kScreenWidth) :  CGRectMake(0, 0, kScreenWidth, kScreenHeight);
  }];
  
}


@end
